import { JSONParseFallback } from '@/utils';

export const dataToForm = (productInfo, productTerms) => {
  const info = JSONParseFallback(JSON.stringify(productInfo)) ?? [];
  const terms = JSONParseFallback(JSON.stringify(productTerms)) ?? [];

  const formData = info.reduce(
    (ret, item) => {
      const { id, contentType, isShow, showContentType, showContentTitle } = item;
      let groupKey = showContentType;
      const isFiles = ['SF', 'PP', 'CF'].includes(showContentType);

      if (isFiles) groupKey = '_files';

      let group = ret[groupKey];
      if (!group) {
        ret[groupKey] = {
          id,
          isShow,
          type: '1',
          title: showContentTitle,
          richTextInfo: null,
          list: [],
        };
        group = ret[groupKey];
      }

      if (contentType === '1') {
        group.type = '1';
        group.richTextInfo = item.richTextInfo;
      }

      if (contentType === '2') {
        group.type = '2';
        group.list.push({
          id,
          isShow,
          showContentType,
          url: item.attachmentUrl,
          name: item.richTextInfo,
          ext: item.attachmentType,
        });

        if (isFiles) {
          group[showContentType] = item.attachmentUrl;
        }
      }
      return ret;
    },
    {
      _terms: {
        type: '2',
        list: terms.map((item) => ({
          id: item.id,
          url: item.termsUrl,
          name: item.termsName,
          ext: item.termsType,
        })),
      },
    },
  );

  console.log('formData', formData);
  return formData;
};

export const formToData = (relationCode, formData, productInfoResp, productTermsResp) => {
  const infoResp = JSONParseFallback(JSON.stringify(productInfoResp)) ?? [];
  const termsResp = JSONParseFallback(JSON.stringify(productTermsResp)) ?? [];
  let { _terms, _files, ...info } = formData;
  _terms ??= { list: [] };
  _files ??= {};

  const infoList = [];
  const termsList = [];

  _terms.list.forEach((fileItem) => {
    if (!fileItem) return;
    let { id = null, url, name, ext } = fileItem;
    if (!url) return;

    termsList.push({
      id,
      relationCode,
      termsUrl: url,
      termsName: name,
      termsType: ext,
      effectiveBeginTime: '1980-01-01 00:00:00',
      effectiveEndTime: '9999-12-31 23:59:59',
      effectiveLongTerm: '1',
    });
  });

  ['SF', 'PP', 'CF'].forEach((showContentType) => {
    const attachmentUrl = _files[showContentType];
    const attachmentType = _files[`${showContentType}_type`];

    if (!attachmentUrl) return;

    const info = _files.list?.find((i) => i.showContentType === showContentType);

    infoList.push({
      id: info?.id,
      relationCode,
      showContentType,
      isShow: '1',
      contentType: '2',
      combinationType: '1',
      attachmentUrl,
      attachmentType,
      richTextInfo: null,
    });
  });

  Object.keys(info).forEach((showContentType) => {
    if (!info[showContentType]) return;
    let { id = null, type, title, list, isShow = '1', richTextInfo } = info[showContentType];

    if (type === '1' && richTextInfo) {
      infoList.push({
        id,
        relationCode,
        showContentType,
        showContentTitle: title,
        isShow,
        contentType: '1',
        combinationType: '1',
        attachmentUrl: null,
        attachmentType: null,
        richTextInfo,
      });
    }
    if (type === '2' && list?.length) {
      list.forEach((fileItem) => {
        if (!fileItem) return;
        let { id = null, url, name, ext } = fileItem;
        if (!url) return;

        infoList.push({
          id,
          relationCode,
          showContentType,
          showContentTitle: title,
          isShow,
          contentType: '2',
          combinationType: '1',
          attachmentUrl: url,
          attachmentType: ext,
          richTextInfo: name,
        });
      });
    }
  });

  const allInfoIds = new Set(infoList.map((v) => v.id).filter(Boolean));
  const allTermIds = new Set(termsList.map((v) => v.id).filter(Boolean));
  const removeInfoList = infoResp.filter((infoItem) => !allInfoIds.has(infoItem.id));
  const removeTermsList = termsResp.filter((termItem) => !allTermIds.has(termItem.id));

  const data = {
    infoList, // 保存的 productInfo
    removeInfoList, // 删除的 productInfo
    termsList, // 保存的条款
    removeTermsList, // 删除的条款
  };

  console.log('formToData', data);
  return data;
};
